<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>统计报表 - 图书馆管理系统</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .statistics-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .statistics-header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .statistics-header h1 {
            color: #333;
            margin-bottom: 10px;
        }
        
        .statistics-header p {
            color: #666;
            font-size: 1.1rem;
        }
        
        .statistics-tabs {
            display: flex;
            justify-content: center;
            margin-bottom: 30px;
            border-bottom: 2px solid #e1e5e9;
        }
        
        .tab-button {
            padding: 12px 24px;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 1rem;
            color: #666;
            border-bottom: 3px solid transparent;
            transition: all 0.3s ease;
        }
        
        .tab-button.active {
            color: #667eea;
            border-bottom-color: #667eea;
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .export-buttons {
            text-align: center;
            margin-bottom: 20px;
        }
        
        .export-buttons button {
            margin: 0 10px;
            padding: 10px 20px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background 0.3s ease;
        }
        
        .export-buttons button:hover {
            background: #5a6fd8;
        }
        
        .date-range-selector {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .date-range-selector input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        
        .date-range-selector button {
            padding: 8px 16px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <div class="statistics-container">
        <div class="statistics-header">
            <h1><i class="fas fa-chart-bar"></i> 统计报表</h1>
            <p>图书馆管理系统数据统计分析</p>
        </div>
        
        <div class="export-buttons">
            <button onclick="window.close()" class="btn btn-outline">
                <i class="fas fa-arrow-left"></i> 返回仪表盘
            </button>
<!--            <button onclick="window.open('index.html', '_blank')" class="btn btn-outline">-->
<!--                <i class="fas fa-home"></i> 主系统-->
<!--            </button>-->
<!--            <button onclick="exportToExcel()">-->
<!--                <i class="fas fa-file-excel"></i> 导出Excel-->
<!--            </button>-->
<!--            <button onclick="exportToPDF()">-->
<!--                <i class="fas fa-file-pdf"></i> 导出PDF-->
<!--            </button>-->
<!--            <button onclick="printReport()">-->
<!--                <i class="fas fa-print"></i> 打印报表-->
<!--            </button>-->
        </div>
        
        <div class="statistics-tabs">
            <button class="tab-button active" onclick="showTab('dashboard')">仪表盘</button>
            <button class="tab-button" onclick="showTab('overview')">概览统计</button>
            <button class="tab-button" onclick="showTab('financial')">财务统计</button>
            <button class="tab-button" onclick="showTab('books')">图书统计</button>
            <button class="tab-button" onclick="showTab('borrows')">借阅统计</button>
            <button class="tab-button" onclick="showTab('users')">用户统计</button>
        </div>
        
        <!-- 仪表盘 -->
        <div id="dashboard" class="tab-content active">
            <div class="page-header">
                <h2>系统仪表板</h2>
                <p>欢迎使用图书馆管理系统 - 实时监控面板</p>
                <div class="dashboard-actions">
                    <button class="btn btn-secondary" onclick="loadDashboard()">
                        <i class="fas fa-sync-alt"></i>
                        刷新数据
                    </button>
                </div>
            </div>
            
            <div class="dashboard-stats">
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-users"></i>
                    </div>
                    <div class="stat-content">
                        <h3 id="totalUsers">0</h3>
                        <p>总用户数</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-book"></i>
                    </div>
                    <div class="stat-content">
                        <h3 id="totalBooks">0</h3>
                        <p>总图书数</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-exchange-alt"></i>
                    </div>
                    <div class="stat-content">
                        <h3 id="totalBorrows">0</h3>
                        <p>总借阅数</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-exclamation-triangle"></i>
                    </div>
                    <div class="stat-content">
                        <h3 id="overdueBorrows">0</h3>
                        <p>逾期借阅</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-calendar-day"></i>
                    </div>
                    <div class="stat-content">
                        <h3 id="todayBorrows">0</h3>
                        <p>今日借阅</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-calendar-check"></i>
                    </div>
                    <div class="stat-content">
                        <h3 id="todayReturns">0</h3>
                        <p>今日归还</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-dollar-sign"></i>
                    </div>
                    <div class="stat-content">
                        <h3 id="totalIncome">¥0</h3>
                        <p>总收入</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon">
                        <i class="fas fa-chart-line"></i>
                    </div>
                    <div class="stat-content">
                        <h3 id="monthlyIncome">¥0</h3>
                        <p>本月收入</p>
                    </div>
                </div>
            </div>
            <div class="dashboard-charts">
                <div class="chart-container">
                    <h3>最近借阅趋势</h3>
                    <canvas id="borrowChart"></canvas>
                </div>
                <div class="chart-container">
                    <h3>图书分类统计</h3>
                    <canvas id="categoryChart"></canvas>
                </div>
            </div>
            
            <div class="dashboard-summary">
                <div class="summary-card">
                    <h3>快速概览</h3>
                    <div class="summary-content">
                        <p><i class="fas fa-info-circle"></i> 系统运行正常，所有服务可用</p>
                        <p><i class="fas fa-clock"></i> 最后更新：<span id="lastUpdateTime">--</span></p>
                        <p><i class="fas fa-chart-line"></i> 今日借阅量较昨日 <span id="borrowTrend">--</span></p>
                    </div>
<!--                    <div class="summary-actions">-->
<!--                        <button class="btn btn-outline" onclick="showTab('overview')">-->
<!--                            <i class="fas fa-chart-bar"></i>-->
<!--                            详细分析-->
<!--                        </button>-->
<!--                    </div>-->
                </div>
            </div>
        </div>
        
        <!-- 概览统计 -->
        <div id="overview" class="tab-content">

            
            <div class="dashboard-stats">
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-users"></i></div>
                    <div class="stat-content">
                        <h3 id="overviewTotalUsers">0</h3>
                        <p>总用户数</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-book"></i></div>
                    <div class="stat-content">
                        <h3 id="overviewTotalBooks">0</h3>
                        <p>总图书数</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-exchange-alt"></i></div>
                    <div class="stat-content">
                        <h3 id="overviewTotalBorrows">0</h3>
                        <p>总借阅数</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-dollar-sign"></i></div>
                    <div class="stat-content">
                        <h3 id="overviewTotalIncome">¥0</h3>
                        <p>总收入</p>
                    </div>
                </div>
            </div>
            
            <div class="dashboard-charts">
                <div class="chart-container">
                    <h3>借阅趋势分析</h3>
                    <canvas id="overviewBorrowChart"></canvas>
                </div>
                <div class="chart-container">
                    <h3>财务收入趋势</h3>
                    <canvas id="overviewFinancialChart"></canvas>
                </div>
            </div>
        </div>
        
        <!-- 财务统计 -->
        <div id="financial" class="tab-content">

            
            <div class="dashboard-stats">
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-money-bill-wave"></i></div>
                    <div class="stat-content">
                        <h3 id="financialTotalIncome">¥0</h3>
                        <p>总收入</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-calendar-alt"></i></div>
                    <div class="stat-content">
                        <h3 id="financialMonthlyIncome">¥0</h3>
                        <p>本月收入</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-exclamation-triangle"></i></div>
                    <div class="stat-content">
                        <h3 id="financialOverdueIncome">¥0</h3>
                        <p>逾期费收入</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-credit-card"></i></div>
                    <div class="stat-content">
                        <h3 id="financialPaymentMethods">0</h3>
                        <p>支付方式</p>
                    </div>
                </div>
            </div>
            
            <div class="dashboard-charts">
                <div class="chart-container">
                    <h3>支付方式分布</h3>
                    <canvas id="paymentMethodChart"></canvas>
                </div>
                <div class="chart-container">
                    <h3>费用类型分布</h3>
                    <canvas id="feeTypeChart"></canvas>
                </div>
            </div>
        </div>
        
        <!-- 图书统计 -->
        <div id="books" class="tab-content">
            <div class="dashboard-stats">
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-book"></i></div>
                    <div class="stat-content">
                        <h3 id="booksTotalCount">0</h3>
                        <p>图书总数</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-tags"></i></div>
                    <div class="stat-content">
                        <h3 id="booksCategoryCount">0</h3>
                        <p>分类数量</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-star"></i></div>
                    <div class="stat-content">
                        <h3 id="booksPopularCount">0</h3>
                        <p>热门图书</p>
                    </div>
                </div>

            </div>
            
            <div class="dashboard-charts">
                <div class="chart-container">
                    <h3>图书分类分布</h3>
                    <canvas id="bookCategoryChart"></canvas>
                </div>
                <div class="table-section">
                    <h3>热门图书排行</h3>
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>排名</th>
                                    <th>图书名称</th>
                                    <th>作者</th>
                                    <th>借阅次数</th>
                                    <th>借阅率</th>
                                    <th>分类</th>
                                </tr>
                            </thead>
                            <tbody id="popularBooksTableBody">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
        </div>
        
        <!-- 借阅统计 -->
        <div id="borrows" class="tab-content">

            
            <div class="dashboard-stats">
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-exchange-alt"></i></div>
                    <div class="stat-content">
                        <h3 id="borrowsTotalCount">0</h3>
                        <p>总借阅数</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-calendar-day"></i></div>
                    <div class="stat-content">
                        <h3 id="borrowsTodayCount">0</h3>
                        <p>今日借阅</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-exclamation-triangle"></i></div>
                    <div class="stat-content">
                        <h3 id="borrowsOverdueCount">0</h3>
                        <p>逾期借阅</p>
                    </div>
                </div>
<!--                <div class="stat-card">-->
<!--                    <div class="stat-icon"><i class="fas fa-clock"></i></div>-->
<!--                    <div class="stat-content">-->
<!--                        <h3 id="borrowsAvgDays">0</h3>-->
<!--                        <p>平均借阅天数</p>-->
<!--                    </div>-->
<!--                </div>-->
            </div>
            
            <div class="dashboard-charts">
                <div class="chart-container">
                    <h3>借阅状态分布</h3>
                    <canvas id="borrowStatusChart"></canvas>
                </div>
                <div class="chart-container">
                    <h3>借阅趋势分析</h3>
                    <canvas id="borrowTrendChart"></canvas>
                </div>
            </div>
        </div>
        
        <!-- 用户统计 -->
        <div id="users" class="tab-content">
            <div class="dashboard-stats">
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-users"></i></div>
                    <div class="stat-content">
                        <h3 id="usersTotalCount">0</h3>
                        <p>用户总数</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-user-plus"></i></div>
                    <div class="stat-content">
                        <h3 id="usersNewCount">0</h3>
                        <p>新增用户</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon"><i class="fas fa-user-check"></i></div>
                    <div class="stat-content">
                        <h3 id="usersActiveCount">0</h3>
                        <p>活跃用户</p>
                    </div>
                </div>
<!--                <div class="stat-card">-->
<!--                    <div class="stat-icon"><i class="fas fa-user-shield"></i></div>-->
<!--                    <div class="stat-content">-->
<!--                        <h3 id="usersAdminCount">0</h3>-->
<!--                        <p>管理员数</p>-->
<!--                    </div>-->
<!--                </div>-->
            </div>
            
            <div class="dashboard-charts">
                <div class="chart-container">
                    <h3>用户角色分布</h3>
                    <canvas id="userRoleChart"></canvas>
                </div>
                <div class="table-section">
                    <h3>活跃用户TOP10</h3>
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>排名</th>
                                    <th>用户名</th>
                                    <th>真实姓名</th>
                                    <th>借阅次数</th>
                                    <th>借阅天数</th>
                                </tr>
                            </thead>
                            <tbody id="usersActiveTableBody">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="api.js"></script>
    <script>
        // 全局日期范围管理
        let currentDateRange = {
            startDate: null,
            endDate: null
        };
        
        // 更新全局日期范围
        function updateGlobalDateRange(startDate, endDate) {
            currentDateRange.startDate = startDate;
            currentDateRange.endDate = endDate;
            console.log('全局日期范围已更新:', startDate, '至', endDate);
        }
        
        // 获取当前日期范围
        function getCurrentDateRange() {
            return currentDateRange;
        }
        
        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeStatistics();
        });
        
        // 初始化统计页面
        function initializeStatistics() {
            console.log('初始化统计页面...');
            
            // 加载仪表盘
            loadDashboard();
        }
        
        // 切换标签页
        function showTab(tabName) {
            // 隐藏所有标签内容
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // 移除所有按钮的激活状态
            document.querySelectorAll('.tab-button').forEach(button => {
                button.classList.remove('active');
            });
            
            // 显示选中的标签内容
            document.getElementById(tabName).classList.add('active');
            
            // 激活对应的按钮
            event.target.classList.add('active');
            
            // 根据标签页加载对应数据
            switch(tabName) {
                case 'dashboard':
                    loadDashboard();
                    break;
                case 'overview':
                    loadOverviewStats();
                    break;
                case 'financial':
                    loadFinancialStats();
                    break;
                case 'books':
                    loadBookStats();
                    break;
                case 'borrows':
                    loadBorrowStats();
                    break;
                case 'users':
                    loadUserStats();
                    break;
            }
        }
        
        // 加载仪表盘数据
        async function loadDashboard() {
            try {
                Utils.showLoading();
                console.log('开始加载仪表盘数据...');
                
                // 获取仪表板数据（不传递日期参数，显示所有数据）
                const dashboardResponse = await StatisticsAPI.getDashboardStats();
                console.log('仪表盘API响应:', dashboardResponse);
                
                if (dashboardResponse.result === 'SUCCESS') {
                    const stats = dashboardResponse.data;
                    console.log('仪表盘统计数据:', stats);
                    
                    // 更新统计数据
                    document.getElementById('totalUsers').textContent = stats.totalUsers || 0;
                    document.getElementById('totalBooks').textContent = stats.totalBooks || 0;
                    document.getElementById('totalBorrows').textContent = stats.totalBorrows || 0;
                    document.getElementById('overdueBorrows').textContent = stats.overdueBorrows || 0;
                    document.getElementById('todayBorrows').textContent = stats.todayBorrows || 0;
                    document.getElementById('todayReturns').textContent = stats.todayReturns || 0;
                    document.getElementById('totalIncome').textContent = '¥' + (stats.totalIncome || 0);
                    document.getElementById('monthlyIncome').textContent = '¥' + (stats.monthlyIncome || 0);
                    
                    console.log('统计数据更新完成，开始加载图表...');
                    
                    // 确保 Chart.js 可用后再加载图表
                    const chartJsLoaded = await ensureChartJsLoaded();
                    if (chartJsLoaded) {
                        loadDashboardCharts(stats);
                    } else {
                        console.error('Chart.js 加载失败，跳过图表渲染');
                        Utils.showMessage('图表库加载失败，图表无法显示', 'warning');
                    }
                    
                    // 更新概览信息
                    updateDashboardSummary(stats);
                    
                    console.log('仪表盘数据加载完成');
                } else {
                    console.error('仪表盘API返回错误:', dashboardResponse);
                    Utils.showMessage(dashboardResponse.message || '加载仪表板数据失败', 'error');
                }
                
            } catch (error) {
                Utils.showMessage('加载仪表板数据失败', 'error');
                console.error('Dashboard load error:', error);
            } finally {
                Utils.hideLoading();
            }
        }
        
        // 加载仪表盘图表数据
        async function loadDashboardCharts(stats) {
            try {
                console.log('开始加载仪表盘图表，统计数据:', stats);
                
                if (typeof Chart === 'undefined') {
                    console.error('Chart.js 未加载');
                    Utils.showMessage('图表库加载失败，请刷新页面重试', 'error');
                    return;
                }
                
                // 验证数据完整性
                if (!stats) {
                    console.error('统计数据为空');
                    Utils.showMessage('统计数据为空，无法生成图表', 'error');
                    return;
                }
                
                // 创建借阅趋势图
                const borrowCtx = document.getElementById('borrowChart');
                if (borrowCtx) {
                    if (stats.borrowTrend && Array.isArray(stats.borrowTrend) && stats.borrowTrend.length > 0) {
                        console.log('创建借阅趋势图，数据:', stats.borrowTrend);
                        new Chart(borrowCtx, {
                            type: 'line',
                            data: {
                                labels: stats.borrowTrend.map(item => item.label),
                                datasets: [{
                                    label: '借阅数量',
                                    data: stats.borrowTrend.map(item => item.value),
                                    borderColor: '#667eea',
                                    backgroundColor: 'rgba(102, 126, 234, 0.1)',
                                    tension: 0.4
                                }]
                            },
                            options: {
                                responsive: true,
                                plugins: {
                                    legend: {
                                        display: false
                                    }
                                }
                            }
                        });
                    } else {
                        console.warn('借阅趋势数据为空或格式不正确');
                        showNoDataMessage(borrowCtx, '暂无借阅趋势数据');
                    }
                }
                
                // 创建分类统计图
                const categoryCtx = document.getElementById('categoryChart');
                if (categoryCtx) {
                    if (stats.categoryStats && Array.isArray(stats.categoryStats) && stats.categoryStats.length > 0) {
                        console.log('创建分类统计图，数据:', stats.categoryStats);
                        new Chart(categoryCtx, {
                            type: 'doughnut',
                            data: {
                                labels: stats.categoryStats.map(stat => stat.label),
                                datasets: [{
                                    data: stats.categoryStats.map(stat => stat.value),
                                    backgroundColor: [
                                        '#667eea', '#f093fb', '#4facfe', '#43e97b', '#ffc107', '#dc3545',
                                        '#17a2b8', '#6f42c1', '#e83e8c', '#fd7e14', '#20c997', '#6c757d',
                                        '#007bff', '#28a745', '#ffc107', '#dc3545', '#17a2b8', '#6f42c1'
                                    ]
                                }]
                            },
                            options: {
                                responsive: true,
                                plugins: {
                                    legend: {
                                        position: 'bottom'
                                    }
                                }
                            }
                        });
                    } else {
                        console.warn('分类统计数据为空或格式不正确');
                        showNoDataMessage(categoryCtx, '暂无分类统计数据');
                    }
                }
                
            } catch (error) {
                console.error('Dashboard charts load error:', error);
                Utils.showMessage('图表加载失败: ' + error.message, 'error');
            }
        }
        
        // 显示无数据消息
        function showNoDataMessage(canvas, message) {
            const ctx = canvas.getContext('2d');
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = '#666';
            ctx.font = '14px Arial';
            ctx.textAlign = 'center';
            ctx.fillText(message, canvas.width / 2, canvas.height / 2);
        }
        
        // 更新仪表盘概览信息
        function updateDashboardSummary(stats) {
            try {
                // 更新最后更新时间
                const now = new Date();
                document.getElementById('lastUpdateTime').textContent = now.toLocaleTimeString();
                
                // 计算借阅趋势
                if (stats.borrowTrend && stats.borrowTrend.length >= 2) {
                    const today = stats.borrowTrend[stats.borrowTrend.length - 1].value;
                    const yesterday = stats.borrowTrend[stats.borrowTrend.length - 2].value;
                    const trend = today > yesterday ? '上升' : today < yesterday ? '下降' : '持平';
                    const trendClass = today > yesterday ? 'text-success' : today < yesterday ? 'text-danger' : 'text-muted';
                    document.getElementById('borrowTrend').innerHTML = `<span class="${trendClass}">${trend}</span>`;
                }
            } catch (error) {
                console.error('Dashboard summary update error:', error);
            }
        }
        
        // 动态加载 Chart.js（多 CDN 兜底）
        async function ensureChartJsLoaded() {
            if (typeof Chart !== 'undefined') return true;
            const urls = [
                'https://cdn.jsdelivr.net/npm/chart.js',
                'https://unpkg.com/chart.js@latest/dist/chart.umd.js',
                'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.min.js'
            ];
            for (const url of urls) {
                try {
                    await loadScript(url, 8000);
                    if (typeof Chart !== 'undefined') return true;
                } catch (e) {
                    console.warn(`Failed to load Chart.js from ${url}:`, e);
                }
            }
            console.error('All Chart.js CDN sources failed');
            return false;
        }
        
        // 动态加载脚本
        function loadScript(src, timeout = 5000) {
            return new Promise((resolve, reject) => {
                const script = document.createElement('script');
                script.src = src;
                script.onload = resolve;
                script.onerror = reject;
                document.head.appendChild(script);
                
                // 超时处理
                setTimeout(() => {
                    if (!script.onload) {
                        reject(new Error(`Script load timeout: ${src}`));
                    }
                }, timeout);
            });
        }
        
        // 加载概览统计
        async function loadOverviewStats() {
            try {
                console.log('开始加载概览统计...');
                
                // 获取基础统计数据
                const dashboardResponse = await StatisticsAPI.getDashboardStats();
                let basicStats = {};
                if (dashboardResponse.result === 'SUCCESS') {
                    basicStats = dashboardResponse.data;
                }
                
                // 获取借阅趋势数据
                const borrowTrendResponse = await StatisticsAPI.getBorrowTrend(30);
                let borrowTrend = [];
                if (borrowTrendResponse.result === 'SUCCESS') {
                    borrowTrend = borrowTrendResponse.data || [];
                }
                
                // 获取财务趋势数据
                const financialTrendResponse = await StatisticsAPI.getFinancialTrend(30);
                let financialTrend = [];
                if (financialTrendResponse.result === 'SUCCESS') {
                    financialTrend = financialTrendResponse.data || [];
                }
                
                // 更新概览统计数据
                document.getElementById('overviewTotalUsers').textContent = basicStats.totalUsers || 0;
                document.getElementById('overviewTotalBooks').textContent = basicStats.totalBooks || 0;
                document.getElementById('overviewTotalBorrows').textContent = basicStats.totalBorrows || 0;
                document.getElementById('overviewTotalIncome').textContent = '¥' + (basicStats.totalIncome || 0);
                
                // 确保 Chart.js 可用后再加载图表
                const chartJsLoaded = await ensureChartJsLoaded();
                if (chartJsLoaded) {
                    loadOverviewCharts({ borrowTrend, financialTrend });
                } else {
                    console.error('Chart.js 加载失败，跳过概览图表渲染');
                    Utils.showMessage('图表库加载失败，图表无法显示', 'warning');
                }
            } catch (error) {
                console.error('加载概览统计失败:', error);
                Utils.showMessage('加载概览统计失败: ' + error.message, 'error');
            }
        }
        
        // 加载概览图表
        function loadOverviewCharts(stats) {
            try {
                if (typeof Chart === 'undefined') {
                    console.error('Chart.js 未加载');
                    return;
                }
                
                // 借阅趋势图
                const borrowCtx = document.getElementById('overviewBorrowChart');
                if (borrowCtx && stats.borrowTrend) {
                    new Chart(borrowCtx, {
                        type: 'line',
                        data: {
                            labels: stats.borrowTrend.map(item => item.label),
                            datasets: [{
                                label: '借阅数量',
                                data: stats.borrowTrend.map(item => item.value),
                                borderColor: '#667eea',
                                backgroundColor: 'rgba(102, 126, 234, 0.1)',
                                tension: 0.4
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    display: false
                                }
                            }
                        }
                    });
                }
            } catch (error) {
                console.error('概览图表加载失败:', error);
            }
            
            // 财务趋势图
            const financialCtx = document.getElementById('overviewFinancialChart');
            if (financialCtx && stats.financialTrend) {
                new Chart(financialCtx, {
                    type: 'bar',
                    data: {
                        labels: stats.financialTrend.map(item => item.label),
                        datasets: [{
                            label: '收入金额',
                            data: stats.financialTrend.map(item => item.value),
                            backgroundColor: 'rgba(75, 192, 192, 0.6)',
                            borderColor: 'rgba(75, 192, 192, 1)',
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: {
                            legend: {
                                display: false
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }
                });
            }
        }
        
        // 加载财务统计
        async function loadFinancialStats() {
            try {
                console.log('开始加载财务统计...');
                
                const response = await StatisticsAPI.getFinancialStats();
                if (response.result === 'SUCCESS') {
                    const stats = response.data;
                    
                    // 更新财务统计数据
                    document.getElementById('financialTotalIncome').textContent = '¥' + (stats.totalIncome || 0);
                    document.getElementById('financialMonthlyIncome').textContent = '¥' + (stats.monthlyIncome || 0);
                    document.getElementById('financialOverdueIncome').textContent = '¥' + (stats.overdueIncome || 0);
                    document.getElementById('financialPaymentMethods').textContent = stats.paymentMethodStats?.length || 0;
                    
                    // 确保 Chart.js 可用后再加载图表
                    const chartJsLoaded = await ensureChartJsLoaded();
                    if (chartJsLoaded) {
                        loadFinancialCharts(stats);
                    } else {
                        console.error('Chart.js 加载失败，跳过财务图表渲染');
                        Utils.showMessage('图表库加载失败，图表无法显示', 'warning');
                    }
                }
            } catch (error) {
                console.error('加载财务统计失败:', error);
                Utils.showMessage('加载财务统计失败: ' + error.message, 'error');
            }
        }
        
        // 加载财务图表
        function loadFinancialCharts(stats) {
            try {
                console.log('开始加载财务图表，统计数据:', stats);
                
                if (typeof Chart === 'undefined') {
                    console.error('Chart.js 未加载');
                    return;
                }
                
                // 支付方式分布图
                const paymentCtx = document.getElementById('paymentMethodChart');
                if (paymentCtx) {
                    if (stats.paymentMethodStats && Array.isArray(stats.paymentMethodStats) && stats.paymentMethodStats.length > 0) {
                        console.log('创建支付方式分布图，数据:', stats.paymentMethodStats);
                        new Chart(paymentCtx, {
                            type: 'doughnut',
                            data: {
                                labels: stats.paymentMethodStats.map(item => item.label),
                                datasets: [{
                                    data: stats.paymentMethodStats.map(item => item.value),
                                    backgroundColor: [
                                        '#667eea',
                                        '#f093fb',
                                        '#4facfe',
                                        '#43e97b'
                                    ]
                                }]
                            },
                            options: {
                                responsive: true,
                                plugins: {
                                    legend: {
                                        position: 'bottom'
                                    }
                                }
                            }
                        });
                    } else {
                        console.warn('支付方式数据为空或格式不正确');
                        showNoDataMessage(paymentCtx, '暂无支付方式数据');
                    }
                }
                
                // 费用类型分布图
                const feeTypeCtx = document.getElementById('feeTypeChart');
                if (feeTypeCtx) {
                    if (stats.feeTypeStats && Array.isArray(stats.feeTypeStats) && stats.feeTypeStats.length > 0) {
                        console.log('创建费用类型分布图，数据:', stats.feeTypeStats);
                        new Chart(feeTypeCtx, {
                            type: 'pie',
                            data: {
                                labels: stats.feeTypeStats.map(item => item.label),
                                datasets: [{
                                    data: stats.feeTypeStats.map(item => item.value),
                                    backgroundColor: [
                                        '#667eea',
                                        '#f093fb',
                                        '#4facfe',
                                        '#43e97b',
                                        '#ffc107',
                                        '#dc3545'
                                    ]
                                }]
                            },
                            options: {
                                responsive: true,
                                plugins: {
                                    legend: {
                                        position: 'bottom'
                                    }
                                }
                            }
                        });
                    } else {
                        console.warn('费用类型数据为空或格式不正确');
                        showNoDataMessage(feeTypeCtx, '暂无费用类型数据');
                    }
                }
                
            } catch (error) {
                console.error('财务图表加载失败:', error);
                Utils.showMessage('财务图表加载失败: ' + error.message, 'error');
            }
        }
        
        // 加载图书统计
        async function loadBookStats() {
            try {
                // 获取基础统计数据
                const dashboardResponse = await StatisticsAPI.getDashboardStats();
                let totalBooks = 0;
                if (dashboardResponse.result === 'SUCCESS') {
                    totalBooks = dashboardResponse.data.totalBooks || 0;
                }
                
                // 获取分类统计数据
                const categoryResponse = await StatisticsAPI.getCategoryStats();
                let categoryStats = [];
                if (categoryResponse.result === 'SUCCESS') {
                    categoryStats = categoryResponse.data || [];
                }
                
                // 获取热门图书数据
                const popularResponse = await StatisticsAPI.getPopularBooks(10);
                let popularBooks = [];
                if (popularResponse.result === 'SUCCESS') {
                    popularBooks = popularResponse.data || [];
                }
                
                // 更新图书统计数据
                document.getElementById('booksTotalCount').textContent = totalBooks;
                document.getElementById('booksCategoryCount').textContent = categoryStats.length;
                document.getElementById('booksPopularCount').textContent = popularBooks.length;
                
                // 确保 Chart.js 可用后再加载图表
                const chartJsLoaded = await ensureChartJsLoaded();
                if (chartJsLoaded) {
                    loadBookCharts({ categoryStats });
                } else {
                    console.error('Chart.js 加载失败，跳过图书图表渲染');
                    Utils.showMessage('图表库加载失败，图表无法显示', 'warning');
                }
                
                // 渲染热门图书表格
                renderPopularBooksTable(popularBooks);
                
            } catch (error) {
                console.error('加载图书统计失败:', error);
                Utils.showMessage('加载图书统计失败: ' + error.message, 'error');
            }
        }
        
        // 加载图书图表
        function loadBookCharts(stats) {
            try {
                if (typeof Chart === 'undefined') {
                    console.error('Chart.js 未加载');
                    return;
                }
                
                // 图书分类分布图
                const categoryCtx = document.getElementById('bookCategoryChart');
                if (categoryCtx && stats.categoryStats) {
                    new Chart(categoryCtx, {
                        type: 'pie',
                        data: {
                            labels: stats.categoryStats.map(item => item.label),
                            datasets: [{
                                data: stats.categoryStats.map(item => item.value),
                                backgroundColor: [
                                    '#667eea', '#f093fb', '#4facfe', '#43e97b', '#ffc107', '#dc3545',
                                    '#17a2b8', '#6f42c1', '#e83e8c', '#fd7e14', '#20c997', '#6c757d',
                                    '#007bff', '#28a745', '#ffc107', '#dc3545', '#17a2b8', '#6f42c1'
                                ]
                            }]
                        },
                        options: {
                            responsive: true,
                            plugins: {
                                legend: {
                                    position: 'bottom'
                                }
                            }
                        }
                    });
                }
            } catch (error) {
                console.error('图书图表加载失败:', error);
            }
        }
        
        // 渲染热门图书表格
        function renderPopularBooksTable(books) {
            const tbody = document.getElementById('popularBooksTableBody');
            if (!tbody) return;
            
            tbody.innerHTML = books.map((book, index) => `
                <tr>
                    <td>${index + 1}</td>
                    <td>${book.bookName}</td>
                    <td>${book.author}</td>
                    <td>${book.borrowCount}</td>
                    <td>${(book.borrowRate * 100).toFixed(1)}%</td>
                    <td>${book.categoryName}</td>
                </tr>
            `).join('');
        }
        
        // 加载借阅统计
        async function loadBorrowStats() {
            try {
                console.log('开始加载借阅统计...');
                
                // 获取基础统计数据
                const dashboardResponse = await StatisticsAPI.getDashboardStats();
                let basicStats = {};
                if (dashboardResponse.result === 'SUCCESS') {
                    basicStats = dashboardResponse.data;
                }
                
                // 获取借阅趋势数据
                const borrowTrendResponse = await StatisticsAPI.getBorrowTrend(30);
                let borrowTrend = [];
                if (borrowTrendResponse.result === 'SUCCESS') {
                    borrowTrend = borrowTrendResponse.data || [];
                }
                
                // 更新借阅统计数据
                document.getElementById('borrowsTotalCount').textContent = basicStats.totalBorrows || 0;
                document.getElementById('borrowsTodayCount').textContent = basicStats.todayBorrows || 0;
                document.getElementById('borrowsOverdueCount').textContent = basicStats.overdueBorrows || 0;
                
                // 确保 Chart.js 可用后再加载图表
                const chartJsLoaded = await ensureChartJsLoaded();
                if (chartJsLoaded) {
                    loadBorrowCharts({ borrowTrend });
                } else {
                    console.error('Chart.js 加载失败，跳过借阅图表渲染');
                    Utils.showMessage('图表库加载失败，图表无法显示', 'warning');
                }
            } catch (error) {
                console.error('加载借阅统计失败:', error);
                Utils.showMessage('加载借阅统计失败: ' + error.message, 'error');
            }
        }
        
        // 加载借阅图表
        function loadBorrowCharts(stats) {
            try {
                if (typeof Chart === 'undefined') {
                    console.error('Chart.js 未加载');
                    return;
                }
                
                // 借阅状态分布图
                const statusCtx = document.getElementById('borrowStatusChart');
                if (statusCtx) {
                    StatisticsAPI.getBorrowStatusStats().then(response => {
                        if (response.result === 'SUCCESS' && response.data) {
                            new Chart(statusCtx, {
                                type: 'doughnut',
                                data: {
                                    labels: response.data.map(item => item.label),
                                    datasets: [{
                                        data: response.data.map(item => item.value),
                                        backgroundColor: [
                                            '#667eea',
                                            '#f093fb',
                                            '#4facfe',
                                            '#43e97b'
                                        ]
                                    }]
                                },
                                options: {
                                    responsive: true,
                                    plugins: {
                                        legend: {
                                            position: 'bottom'
                                        }
                                    }
                                }
                            });
                        }
                    }).catch(error => {
                        console.error('获取借阅状态统计失败:', error);
                    });
                }
            } catch (error) {
                console.error('借阅图表加载失败:', error);
            }
            
            // 借阅趋势图
            const trendCtx = document.getElementById('borrowTrendChart');
            if (trendCtx && stats.borrowTrend) {
                new Chart(trendCtx, {
                    type: 'line',
                    data: {
                        labels: stats.borrowTrend.map(item => item.label),
                        datasets: [{
                            label: '借阅数量',
                            data: stats.borrowTrend.map(item => item.value),
                            borderColor: '#667eea',
                            backgroundColor: 'rgba(102, 126, 234, 0.1)',
                            tension: 0.4
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: {
                            legend: {
                                display: false
                            }
                        }
                    }
                });
            }
        }
        
        // 加载用户统计
        async function loadUserStats() {
            try {
                // 获取基础统计数据
                const dashboardResponse = await StatisticsAPI.getDashboardStats();
                let basicStats = {};
                if (dashboardResponse.result === 'SUCCESS') {
                    basicStats = dashboardResponse.data;
                }
                
                // 获取新增用户数量（最近7天）
                const newUsersResponse = await StatisticsAPI.getNewUsersCount();
                let newUsersCount = 0;
                if (newUsersResponse.result === 'SUCCESS') {
                    newUsersCount = newUsersResponse.data || 0;
                }
                
                // 获取活跃用户数量（最近7天有借阅记录）
                const activeUsersCountResponse = await StatisticsAPI.getActiveUsersCount();
                let activeUsersCount = 0;
                if (activeUsersCountResponse.result === 'SUCCESS') {
                    activeUsersCount = activeUsersCountResponse.data || 0;
                }
                
                // 获取活跃用户排行数据
                const activeUsersResponse = await StatisticsAPI.getActiveUsers(10);
                let activeUsers = [];
                if (activeUsersResponse.result === 'SUCCESS') {
                    activeUsers = activeUsersResponse.data || [];
                }
                
                // 更新用户统计数据
                document.getElementById('usersTotalCount').textContent = basicStats.totalUsers || 0;
                document.getElementById('usersNewCount').textContent = newUsersCount;
                document.getElementById('usersActiveCount').textContent = activeUsersCount;
                
                // 确保 Chart.js 可用后再加载图表
                const chartJsLoaded = await ensureChartJsLoaded();
                if (chartJsLoaded) {
                    loadUserCharts(basicStats);
                } else {
                    console.error('Chart.js 加载失败，跳过用户图表渲染');
                    Utils.showMessage('图表库加载失败，图表无法显示', 'warning');
                }
                
                // 加载活跃用户表格
                renderUsersActiveTable(activeUsers);
            } catch (error) {
                console.error('加载用户统计失败:', error);
                Utils.showMessage('加载用户统计失败: ' + error.message, 'error');
            }
        }
        
        // 加载用户图表
        function loadUserCharts(stats) {
            try {
                if (typeof Chart === 'undefined') {
                    console.error('Chart.js 未加载');
                    return;
                }
                
                // 用户角色分布图
                const roleCtx = document.getElementById('userRoleChart');
                if (roleCtx) {
                    StatisticsAPI.getUserRoleStats().then(response => {
                        if (response.result === 'SUCCESS' && response.data) {
                            new Chart(roleCtx, {
                                type: 'pie',
                                data: {
                                    labels: response.data.map(item => item.label),
                                    datasets: [{
                                        data: response.data.map(item => item.value),
                                        backgroundColor: [
                                            '#667eea',
                                            '#f093fb',
                                            '#4facfe'
                                        ]
                                    }]
                                },
                                options: {
                                    responsive: true,
                                    plugins: {
                                        legend: {
                                            position: 'bottom'
                                        }
                                    }
                                }
                            });
                        }
                    }).catch(error => {
                        console.error('获取用户角色统计失败:', error);
                    });
                }
            } catch (error) {
                console.error('用户图表加载失败:', error);
            }
        }
        
        // 渲染活跃用户表格
        function renderUsersActiveTable(users) {
            const tbody = document.getElementById('usersActiveTableBody');
            if (!tbody) return;
            
            tbody.innerHTML = users.map((user, index) => `
                <tr>
                    <td>${index + 1}</td>
                    <td>${user.username}</td>
                    <td>${user.realName}</td>
                    <td>${user.borrowCount}</td>
                    <td>${user.borrowDays}</td>
                </tr>
            `).join('');
        }
        
        // 导出功能
        function exportToExcel() {
            alert('Excel导出功能开发中...');
        }
        
        function exportToPDF() {
            alert('PDF导出功能开发中...');
        }
        
        function printReport() {
            window.print();
        }
    </script>
</body>
</html>
